import { goodslist, goodscount } from '../../../request/api'
const state = {
    goodslist: [],
    size: 2,
    page: 1,
    count: 0
}

const getters = {
    getGoods(state) {
        return state.goodslist
    },
    getCount(state) {
        return state.count
    },
    //返回当前显示条数
    getSize(state) {
        return state.size
    }
}

const mutations = {
    REQ_LIST(state, payLoad) {
        state.goodslist = payLoad
    },
    REQ_COUNT(state, payLoad) {
        state.count = payLoad
    },
    CHANGE_PAGE(state, payLoad) {
        state.page = payLoad
    }
}

const actions = {
    getGoodsAction(context) {
        goodslist({
            size: context.state.size,
            page: context.state.page
        })
            .then(res => {
                if (res.code == 200) {
                    context.commit('REQ_LIST', res.list)
                    let list = res.list ? res.list : []
                    if (context.state.page != 1 && list.length == 0) {
                        context.dispatch('changePageAction', context.state.page - 1)
                    }
                }
            })
    },
    getCountAction({ commit }) {
        goodscount()
            .then(res => {
                console.log(res, 88888)
                if (res.code == 200) {
                    commit('REQ_COUNT', res.list[0].total)
                }
            })
    },
    //封装一个切换页码的行动   
    changePageAction(context, payLoad) {
        context.commit('CHANGE_PAGE', payLoad)
        context.dispatch('getGoodsAction')
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}